package org.metasketch.demo.project.load;

import java.io.File;

import org.metasketch.demo.project.DEMOProject;
import org.metasketch.graphics.Diagram;
import org.metasketch.graphics.DiagramSet;
import org.metasketch.logger.Log;
import org.metasketch.model.loader.DefaultModelReader;
import org.metasketch.model.loader.IGraphDatabase;
import org.metasketch.model.loader.transform.ModelTransformer;

public class DEMODiagramLoader {

	public static DiagramSet loadDiagrams(File diagramDirectory,
			DEMOProject project) throws Throwable {

		DiagramSet diagrams = new DiagramSet();

		File[] files = diagramDirectory.listFiles();
		for (int i = 0; i < files.length; i++) {
			File file = files[i];
			if (file.isFile() && file.getName().endsWith(".xml")) {
				loadDiagram(file, diagrams);
			}
		}

		project.setDiagrams(diagrams);

		return diagrams;
	}

	private static void loadDiagram(File file, DiagramSet diagrams)
			throws Throwable {

		Log.print("Loading diagram: " + file.getName() + "...");
		// System.out.flush();

		DefaultModelReader reader = new DefaultModelReader();
		IGraphDatabase diagramGraph = reader.readFile(file);

		Log.println("done.");
		// System.out.flush();
		Log.print("Creating diagram: " + file.getName() + "...");
		// System.out.flush();
		// transform graph into model

		// DEMODiagram diagram = null;DEMODiagram
		//
		// diagram = DEMODiagramTransformer.transform(diagramGraph);

		Diagram diagram = new Diagram();

		ModelTransformer.transform(diagramGraph, diagram, "Diagram",
				"org.metasketch.graphics.", false);

		diagrams.getDiagrams().add(diagram);

		Log.println("done.");
		// System.out.flush();

	}

}
